package com.graduate.emos.wx.config;

import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
public class SwaggerConfig {

    /**
     * @return Docket:Swagger的各种配置信息都封装到Docket对象里
     */
    @Bean    //返回给spring
    public Docket createRestApi(){
        //创建docket对象
        Docket docket = new Docket(DocumentationType.OAS_30);
        //1.为Swagger添加标题信息
        //ApiInfoBuilder 用于在Swagger界面添加各种信息
        ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title("EMOS在线办公系统").description("毕设项目测试");
        ApiInfo info = builder.build();
        docket.apiInfo(info);

        //2.设置要添加到Swagger界面进行测试的方法
        ApiSelectorBuilder selectorBuilder = docket.select();
        //选择所有包下的所有类的所有方法
        selectorBuilder.paths(PathSelectors.any());
        //选择方法上有@ApiOperation注解的方法添加到Swagger界面
        selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
        docket = selectorBuilder.build();

        //3.让swagger支持jwt,当使用swagger调用受jwt认证保护的方法必须先提交参数如令牌
        //设置客户端的token令牌放置的位置以及参数名
        ApiKey apiKey = new ApiKey("token","token", In.HEADER.toValue());
        //封装到一个List列表
        List<SecurityScheme> apiKeyList = Collections.singletonList(apiKey);
        //将apiKeyList添加到docket
        docket.securitySchemes(apiKeyList);

        //设定token令牌有效时的作用域,global为全局有效
        AuthorizationScope scope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] scopes = {scope};
        //存储令牌和作用域
        SecurityReference reference = new SecurityReference("token",scopes);
        List<SecurityReference> referenceList = new ArrayList<>();
        referenceList.add(reference);
        SecurityContext context = SecurityContext.builder().securityReferences(referenceList).build();
        List<SecurityContext> ctxList = new ArrayList<>();
        ctxList.add(context);
        docket.securityContexts(ctxList);
        return docket;
    }
}
